/*********************************************************
          File Name:readn_writen.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sun 30 Aug 2015 10:38:54 AM CST
**********************************************************/

// copy from APUE

ssize_t readn(int fd, void *ptr, size_t n)
{
        size_t nleft;
        size_t nread;

        nleft = n;

        while(nleft > 0)
        {
                if((nread = read(fd, ptr, nleft)) < 0)
                {
                        if(nleft == n)
                                return -1;
                        else
                                break; /* may be interrupted by signal, return amount read so far */
                }
                else if(nread == 0)
                        break;                          /* EOF */

                nleft -= nread;
                ptr += nread;
        }

        return (n - nleft);
}

ssize_t writen(int fd, const void *ptr, size_t n)
{
        size_t nleft;
        ssize_t nwritten;

        nleft = n;

        while(nleft > 0)
        {
                if((nwritten = write(fd, ptr, n)) < 0)
                {
                        if(nleft == n)
                                return -1;
                        else
                                break;  /* may be interrupted by signal, return amount written so far */
                }
                else if(nwritten == 0)
                        break;

                nleft -= nwritten;
                ptr += nwritten;
        }

        return (n - nleft);
}
